<?php
/**
 * Created by PhpStorm.
 * User: lih
 * Date: 2017/6/22
 * Time: 23:09
 */

namespace frontend\api\action;

use Yii;
use yii\db\Query;
use common\models\User;

class BaseAction
{

    /**
     * @param $arrayData array
     * @param $returnData array
     * @throws \Exception
     */
    public function runAction($arrayData, &$returnData)
    {

    }

    /**
     * @param $param string
     * @return string
     */
    public function trimNullParam($param)
    {
        return ($param !== null) ? $param : "";
    }

    /**
     * @param $tableName string
     * @return string
     */
    public function getDzTableName($tableName) {
        return "xdz_" . $tableName;
    }

    /**
     * @param $uid string
     * @return array|null
     */
    public function getUserDataByUid($uid)
    {
        $userData = null;
        $user = User::findIdentity($uid);
        if($user !== null) {
            $userData = array();
            $userData['uid'] = $user->getId();
            $userData['utype'] = $user->utype;
            $userData['username'] = $user->username;
        }
        return $userData;
    }


    /**
     * @param $query yii\db\Query
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function queryPageData($query, $p, $pageSize) {
        $p = intval($p);
        $pageSize = intval($pageSize);
        if($p <= 0) {
            $p = 1;
        }

        $returnData = array();
        if($query == null) {
            return $returnData;
        }
        $dbConn = Yii::$app->db;
        $queryCount = (new Query())->select('count(*)')
            ->from($query->from)
            ->where($query->where, $query->params)
            ->createCommand($dbConn)
            ->queryScalar();
        $pageCount = ceil($queryCount / $pageSize);
        if($p <= $pageCount) {
            $dataQuery = (new Query())->select('*')
                ->from($query->from)
                ->where($query->where, $query->params)
                ->orderBy($query->orderBy)
                ->offset(($p - 1) * $pageSize)
                ->limit($pageSize)
                ->createCommand($dbConn)
                ->queryAll();
            $returnData['data'] = $dataQuery;
            $returnData['p'] = '';
            if($p < $pageCount) {
                $returnData['p'] = '' . ($p + 1);
            }
        }
        return $returnData;
    }

}

